package org.zfes.snowier.cloud.zbss.cms.words.service.impl;

import java.util.Map;
import java.util.Optional;
import org.zfes.snowier.core.data.DataSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.zfes.snowier.core.util.ZBeanUtil;
import org.zfes.snowier.core.util.ZDateUtil;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.zfes.snowier.core.util.ZAlert;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.common.dao.params.ParamMap;
import org.zfes.snowier.cloud.zbss.cms.words.service.ICmsWordsSearchService;
import org.zfes.snowier.cloud.zbss.cms.words.dao.CmsWordsSearchMapper;
import org.zfes.snowier.cloud.zbss.cms.words.model.CmsWordsSearch;
import java.util.stream.Stream;
@Service
public class CmsWordsSearchServiceImpl implements ICmsWordsSearchService{
 	@Autowired
	private CmsWordsSearchMapper cmsWordsSearchMapper;
 	
	@Transactional(rollbackFor=Exception.class)
 	@Override
	public void createCmsWordsSearch(CmsWordsSearch cmsWordsSearch) {
		ZBeanUtil.setCreateInfo(cmsWordsSearch);
		ZBeanUtil.validateBean(cmsWordsSearch);
		//汉字转为拼音
		String words=cmsWordsSearch.getNameInitial();
		String nameInitial=converterToFirstSpell( words);
		cmsWordsSearch.setNameInitial(nameInitial);
		cmsWordsSearch.setCreateTime(ZDateUtil.newDate());
		cmsWordsSearch.setUpdateTime(ZDateUtil.newDate());
		cmsWordsSearchMapper.insertSelective(cmsWordsSearch);
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<CmsWordsSearch> loadCmsWordsSearchById(Long id) {
		if(id!=null){
			return Optional.ofNullable(cmsWordsSearchMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
		
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateCmsWordsSearch(CmsWordsSearch cmsWordsSearch) {
		ZBeanUtil.validateBean(cmsWordsSearch);
		//汉字转为拼音
		String words=cmsWordsSearch.getNameInitial();
		String nameInitial=converterToFirstSpell( words);
		cmsWordsSearch.setNameInitial(nameInitial);
		cmsWordsSearch.setUpdateTime(ZDateUtil.newDate());
		cmsWordsSearchMapper.updateByPrimaryKeySelective(cmsWordsSearch);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void deleteCmsWordsSearch(Long id) {
		ZAssert.notNull(id, "请选择要操作的数据");
		cmsWordsSearchMapper.updateStatus(id, Byte.valueOf("-1"),ZDateUtil.newDate());
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void setCmsWordsSearchStatus(Long id, Byte status) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(status, "状态参数错误");
		if(!Stream.of(new Byte[] {-1,0,1}).anyMatch(val->val.equals(status))) {
			ZAlert.serviceLogicalError("状态参数错误");
		}
		cmsWordsSearchMapper.updateStatus( id,  status,ZDateUtil.newDate()) ;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadCmsWordsSearchDataSet(Map<String, Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		pm.getObj("words").ifPresent(v->pm.updateParam("words", "%"+v+"%"));
		DataSet ds=DataSet.newDS2(cmsWordsSearchMapper.selectListCount(pm), cmsWordsSearchMapper.selectMapListPage(pm));
		return ds;
	}
	@Transactional(rollbackFor=Exception.class)
	@Override
	//后台：推荐、优先级设置
	public void setCmsWordsSearchPriorityAndIsRecommend(Long id, Integer priority, Byte isRecommend) {
		ZAssert.notNull(id, "请选择要操作的数据");
		ZAssert.notNull(priority, "优先级参数错误");
		ZAssert.notNull(isRecommend, "推荐参数错误");
		if(!Stream.of(new Byte[] {0,1}).anyMatch(val->val.equals(isRecommend))) {
			ZAlert.serviceLogicalError("推荐参数错误");
		}
		CmsWordsSearch cmsWordsSearch=cmsWordsSearchMapper.selectByPrimaryKey(id);
		ZBeanUtil.validateBean(cmsWordsSearch);
		cmsWordsSearch.setPriority(priority);
		cmsWordsSearch.setIsRecommend(isRecommend);
		cmsWordsSearch.setUpdateTime(ZDateUtil.newDate());
	    updateCmsWordsSearch(cmsWordsSearch);
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	//被调用：按搜索词查找
	public Optional<CmsWordsSearch> selectCmsWordsSearchByWords(String words) {
		if(!words.isEmpty()){
			return Optional.ofNullable(cmsWordsSearchMapper.selectCmsWordsSearchByWords(words));
		}
		return Optional.empty();
	}
	 /**
     * 汉字转换位汉语拼音首字母，英文字符不变
     *
     * @param chines 汉字
     * @return 拼音
     */
	public static String converterToFirstSpell(String chinese) {
        String pinyinName = "";
        char[] nameChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < nameChar.length; i++) {
            if (nameChar[i] > 128) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(
                            nameChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }
    
}